/**
 * 权限服务
 * 作者：GodMainCode
 * 创建时间：2024-01-17
 * 修改时间：2024-01-17
 * 修改人：GodMainCode
 */

import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, TreeRepository } from 'typeorm';
import { Permission } from './entities/permission.entity';
import { CreatePermissionDto } from './dto/create-permission.dto';
import { UpdatePermissionDto } from './dto/update-permission.dto';

@Injectable()
export class PermissionService {
  constructor(
    @InjectRepository(Permission)
    private readonly permissionRepository: Repository<Permission>,
    @InjectRepository(Permission)
    private readonly treeRepository: TreeRepository<Permission>,
  ) {}

  /**
   * 创建权限
   * @param createPermissionDto 创建权限数据
   * @returns Promise<Permission> 创建的权限信息
   */
  async create(createPermissionDto: CreatePermissionDto): Promise<Permission> {
    const { parent_id, ...permissionData } = createPermissionDto;

    const permission = this.permissionRepository.create(permissionData);

    if (parent_id) {
      const parent = await this.findOne(parent_id);
      permission.parent = parent;
    }

    return await this.permissionRepository.save(permission);
  }

  /**
   * 获取权限树
   * @returns Promise<Permission[]> 权限树
   */
  async findTree(): Promise<Permission[]> {
    return await this.treeRepository.findTrees({
      relations: ['roles'],
    });
  }

  /**
   * 获取所有权限（扁平结构）
   * @returns Promise<Permission[]> 权限列表
   */
  async findAll(): Promise<Permission[]> {
    return await this.permissionRepository.find({
      where: { is_deleted: 0 },
      relations: ['parent', 'children', 'roles'],
      order: { sort: 'ASC' },
    });
  }

  /**
   * 获取权限详情
   * @param id 权限ID
   * @returns Promise<Permission> 权限信息
   */
  async findOne(id: number): Promise<Permission> {
    const permission = await this.permissionRepository.findOne({
      where: { id, is_deleted: 0 },
      relations: ['parent', 'children', 'roles'],
    });

    if (!permission) {
      throw new NotFoundException(`ID为${id}的权限不存在`);
    }

    return permission;
  }

  /**
   * 更新权限
   * @param id 权限ID
   * @param updatePermissionDto 更新权限数据
   * @returns Promise<Permission> 更新后的权限信息
   */
  async update(id: number, updatePermissionDto: UpdatePermissionDto): Promise<Permission> {
    const { parent_id, ...permissionData } = updatePermissionDto;
    const permission = await this.findOne(id);

    if (parent_id) {
      const parent = await this.findOne(parent_id);
      permission.parent = parent;
    }

    Object.assign(permission, permissionData);
    return await this.permissionRepository.save(permission);
  }

  /**
   * 删除权限
   * @param id 权限ID
   */
  async remove(id: number): Promise<void> {
    const permission = await this.findOne(id);
    permission.is_deleted = 1;
    await this.permissionRepository.save(permission);
  }

  /**
   * 根据权限标识查找权限
   * @param code 权限标识
   * @returns Promise<Permission> 权限信息
   */
  async findByCode(code: string): Promise<Permission | null> {
    return await this.permissionRepository.findOne({
      where: { code, is_deleted: 0 },
      relations: ['roles'],
    });
  }
} 